package com.ti.demo.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ti.demo.entity.CityRequest;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.function.FunctionToolCallback;
import org.springframework.web.client.RestClient;

import java.util.function.Function;

/**
 * @description: com.ti.demo.tool
 * @Author Triagen
 * @Date 2025/10/9 15:34
 */
public class WeatherTools {

    public static ToolCallback getCityId(RestClient restClient) {
        return FunctionToolCallback.builder("getCityId", (Function<CityRequest, String>) cityRequest -> {
                    String body = restClient.get().uri("/map/weather/1").retrieve().body(String.class);
                    JSONObject jsonObject = JSON.parseObject(body);
                    return jsonObject.getJSONObject("data").getJSONArray("city").stream()
                            .filter(o -> cityRequest.getCityName().equals(((JSONArray) o).getString(1)))
                            .findFirst()
                            .map(o -> ((JSONArray) o).getString(0))
                            .get();
                })
                .inputType(CityRequest.class)
                .description("To get weather info, we need to use cityId, this tool is used to get cityId from cityName")
                // 输入inputType 后会自动解析，这里注释掉，仅供参考
//                .inputSchema("""
//                        {
//                          "$schema" : "https://json-schema.org/draft/2020-12/schema",
//                          "type" : "object",
//                          "properties" : {
//                            "cityName" : {
//                              "type" : "string",
//                              "description" : "cityName, the language should be Chinese"
//                            }
//                          },
//                          "required" : [ "cityName" ],
//                          "additionalProperties" : false
//                        }
//                        """)
                .build();
    }
}
